const path = require('path');
const webpack = require("webpack");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
let HtmlWebpackPlugin = require('html-webpack-plugin');

// 环境变量配置  dev / online
let WEBPACK_ENV = process.env.WEBPACK_ENV || 'dev';
let publicPath = 'dev' === WEBPACK_ENV? '/dist/' : '//s.searchuang.com/mall/dist';

// css单独打包
const extractCSS = new ExtractTextPlugin('css/[name].css');

// 获取HtmlWebpackPlugin参数方法
let getHtmlConfig = (title, name) => {
	return {
				title: title,
				filename: `view/${name}.html`,
				template: `./src/view/${name}.html`,
				// favicon: './favicon.ico',
				chunks: ['commons', name],
				hash: true,
				minify: {
					minifyCSS: true,	// 缩小css样式 ---> style标签
					minifyJS: true,		// 缩小js	   ---> script标签
					removeComments: true, // 剥离HTML注释
					collapseWhitespace: true //删除空白符与换行符
				}
	}
};

// 打包独立通用模块到js/base.js
let CommonsChunk = new webpack.optimize.CommonsChunkPlugin({
	name: "commons",
	filename: "js/base.js",
});

let webpackConfig = {
	entry: {
		'commons': ['./src/page/commons/index.js'],
		'index': ['./src/page/index/index.js'],
		'login': ['./src/page/login/index.js']
	},
	output: {
		path: path.resolve(__dirname, 'dist'),	
		publicPath,
		filename: 'js/[name].js'
	},
	module:{
		rules:[
			{
				test: /\.css$/,
				use: extractCSS.extract([
					'css-loader', 'postcss-loader'
				])
			},
			{
				test: /\.s[ac]ss$/,
				use: ExtractTextPlugin.extract({
		          fallback: 'style-loader',
		          use: ['css-loader', 'postcss-loader', 'sass-loader']
		        })
			},
			{
		      test: /\.js$/,
		      exclude: /(node_modules|bower_components)/,
		      use: {
		        loader: 'babel-loader',
		        options: {
		          presets: ['env']
		        }
		      }
		    },
			{
		      test: /\.(jpg|png|gif|woff|svg|eot|ttf)\??.*$/i,
		      use: [
				{
					loader: 'file-loader',
					options: {
						limit: 2000,
						name: 'resource/[name].[ext]'
					}  
				},
				'image-webpack-loader'
			  ]
		    }
		]
	},
	externals: {
		jquery: 'window.jQuery'
	},
	resolve: {
		alias: {
			'node_modules': path.resolve(__dirname, 'node_modules'),
			'util': path.resolve(__dirname, 'src/util'),
			'service': path.resolve(__dirname, 'src/service'),
			'page': path.resolve(__dirname, 'src/page'),
			'image': path.resolve(__dirname, 'src/image'),
			'view': path.resolve(__dirname, 'src/view')
		}
	},
	plugins: [
		extractCSS,
		CommonsChunk,
		new HtmlWebpackPlugin( getHtmlConfig('首页', 'index') ),
		new HtmlWebpackPlugin( getHtmlConfig('登录', 'login') )
	]
}

if('dev' === WEBPACK_ENV){
	webpackConfig.entry.commons.push('webpack-dev-server/client?http://localhost:8080/');
}

module.exports = webpackConfig;